#-*-coding:utf-8-*-
# 使用 Connector/Python 进行查询操作。
import mysql.connector
import ConfigParser

from mysql.connector import errorcode
import logging.config

logging.config.fileConfig("conf/logger.conf")
logger = logging.getLogger("alertserver")
def connDB():
    # 创建连接
    try:
        cf = ConfigParser.ConfigParser()
        cf.read("conf/db.ini")
        db_port = cf.getint("db", "db_port")
        db_user = cf.get("db", "db_username")
        db_password = cf.get("db", "db_password")
        db_host = cf.get("db", "db_host")
        db_database = cf.get("db", "db_database")
        config = {
                      'user':db_user, 
                      'password':db_password, 
                      'host':db_host, 
                      'port':db_port,  
                      'database':db_database}
        conn = mysql.connector.connect(**config)
        cur = conn.cursor()
    #except Exception , e:
    #        print e   
    except mysql.connector.Error as err:
        if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
            print("Connect DB Something is wrong with your user name or password")
            logger.info("Connect DB Something is wrong with your user name or password")
        elif err.errno == errorcode.ER_BAD_DB_ERROR:
            print("Connect DB Database does not exist")
            logger.info("Connect DB Database does not exist")
        else:
            print("Connect DB failure"+err)
            logger.info("Connect DB failure"+err)
    return (conn,cur);
    
def exeUpdate(conn,cur,sql):  
    try:              #更新或插入操作
        sta=0
        cur.execute(sql);
        sta=conn.commit();
    except mysql.connector.Error as e: 
        print('update or insert datas error!{}'.format(e)) 
        logger.info("update or insert datas error!{}".format(e))
    return (sta);

def exeDelete(conn,cur,IDs):
    try:
        sta=0;
        for eachID in IDs.split('，'):
            print(eachID)
            sql="delete from student where id="+str(eachID)
            sta+=cur.execute(sql);
            conn.commit();
    except  mysql.connector.Error as e:                  #删除操作
        print('delete datas error!{}'.format(e)) 
        logger.info("delete datas error!{}".format(e))
    return (sta);   
def exeQuery(cur,sql):
    try: 
        print(sql+"-----")
        cur.execute(sql);
        resultvalue =cur.fetchall()  
    except mysql.connector.Error as e: 
        print('query datas error!{}'.format(e)) 
        logger.info("query datas error!{}".format(e))
        return (cur);
    return resultvalue

def connClose(conn,cur):                    #关闭连接，释放资源
    cur.close();
    conn.close();
    
